package smarthouse.ejb;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import smarthouse.conv.Conversions;
import smarthouse.dto.HouseDTO;
import smarthouse.model.House;

/**
 * Session Bean implementation class HouseDAO
 */
@Stateless
@Local
public class HouseDAO implements HouseDAORemote {

	@EJB
	Conversions conv;

	@PersistenceContext
	EntityManager em;

	/**
	 * Default constructor.
	 */
	public HouseDAO() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public HouseDTO getHousebyId(int id) {
		TypedQuery<House> usersReturn = em.createNamedQuery("House.findAll",
				House.class);

		List<House> users = usersReturn.getResultList();
		for (House u : users) {
			if (u.getHouseId() == id){
				return conv.house_C_2_DTO(u);}
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean addHouse(HouseDTO user) {
		House u = em.find(House.class, user.getHouseId());

		if (u == null) {
			em.persist(conv.house_DTO_2_C(user));
			return true;
		} else {
			em.merge(conv.house_DTO_2_C(user));
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean updateHouse(HouseDTO user) {
		House u = em.find(House.class, user.getHouseId());

		if (u == null) {
			return false;
		} else {
			em.merge(conv.house_DTO_2_C(user));
			return true;
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean removeHouse(int id) {
		House u = em.find(House.class, id);

		if (u == null) {
			return false;
		} else {
			em.remove(id);
			return true;
		}

	}

}
